package com.cashmama.market.api.application.controller;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.cashmama.market.api.application.annos.SignIgnore;
import com.cashmama.market.api.application.annos.VisitorAccessible;
import com.cashmama.market.api.domain.vo.RequestLocalInfo;
import com.cashmama.market.api.infras.config.ApolloConfigUtil;
import com.cashmama.market.api.infras.consts.RedisKeyConsts;
import com.fqgj.base.services.amazon.AmazonS3Service;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.api.Response;
import com.fqgj.xjd.user.client.UserService;
import com.fqgj.xjd.user.client.response.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: yujianfu (mr.vencnet@gmail.com)
 * Date: 2019-11-25
 * Time: 11:08
 */
@RestController
public class OkController {

    private static final Logger LOGGER = LoggerFactory.getLogger(OkController.class);

    @Autowired
    RedisClient redisClient;

    @Autowired
    private ApolloConfigUtil apolloConfigUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private AmazonS3Service amazonS3Service;



    @VisitorAccessible
    @SignIgnore
    @RequestMapping("/ok")
    public String ok() {
        Response<User> aaa = userService.getUserByUserCode("aaa");
        return "ok";
    }

    @VisitorAccessible
    @SignIgnore
    @RequestMapping("/ok2")
    public String ok2() {
        try {
            String userCode = "12312312312";
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String fileName = apolloConfigUtil.isServerTest() ? "moveClientSpace/test/" + userCode + "/" + uuid : "moveClientSpace/" + userCode + "/" + uuid + "_B";



        } catch (Exception e) {
            e.printStackTrace();
        }
        return "okaaaa";
    }

    @VisitorAccessible
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String test() {
        System.out.println(RequestLocalInfo.getRequestBasicInfo());
        return "ok";
    }

    @RequestMapping("/configok")
    @SignIgnore
    @VisitorAccessible
    public String configok() {
        String value = apolloConfigUtil.getForceUpdateAndroidUrl();
        LOGGER.info("configok,{}", value);
        return "configok";
    }

    @SignIgnore
    @VisitorAccessible
    @RequestMapping(value = "/deleteCache/{userCode}/{appCode}", method = RequestMethod.GET)
    public String deleteCache(@PathVariable("userCode") String userCode, @PathVariable("appCode") String appCode) {
        redisClient.del(RedisKeyConsts.SMS_REPORT_KEY, userCode);
        redisClient.del(RedisKeyConsts.APPVO_CACHA, appCode);
        redisClient.del(RedisKeyConsts.ALOGO_360_ACCESS_TOKEN_KEY);
        redisClient.del(RedisKeyConsts.USER_TIPS_SCROLLER_DDD_KEY);
        redisClient.del(RedisKeyConsts.USER_LEVEL_CONFIG_KEY);
        redisClient.del(RedisKeyConsts.USER_CHECK_IN_ONE_DAY, userCode);
        redisClient.del(RedisKeyConsts.ADVANCE_LICENCE_KEY);
        return "ok";
    }

    @SignIgnore
    @VisitorAccessible
    @RequestMapping(value = "/delete/{mobile}/{merchantCode}", method = RequestMethod.GET)
    public String merchantCode(@PathVariable("mobile") String mobile, @PathVariable("merchantCode") String merchantCode) {
        redisClient.del(RedisKeyConsts.COLLISION_DATA_KEY, mobile, merchantCode);
        return "ok";
    }

    @SignIgnore
    @VisitorAccessible
    @RequestMapping(value = "/product/{appCode}", method = RequestMethod.GET)
    public String product(@PathVariable("appCode") String appCode) {
        return redisClient.get(RedisKeyConsts.APPVO_CACHA, appCode);
    }

    @SignIgnore
    @VisitorAccessible
    @RequestMapping(value = "/message/{message}", method = RequestMethod.GET)
    public String message(@PathVariable("message") String message) {
//        MessageMQ messageMQ = new MessageMQ();
//        messageMQ.setMessage(message);
//        messageMQ.setTag(MQTagEnum.ORDER);
//        messageMQ.setMessageId(UUID.randomUUID().toString().replaceAll("-", ""));
//        messageMQHandler.send(messageMQ);
        return "ok";
    }

//    @SignIgnore
//    @VisitorAccessible
//    @RequestMapping(value = "/moveData/{type}", method = RequestMethod.GET)
//    public String moveData(@PathVariable("type") Integer type) {
//        if (type == null) {
//            return "type can't be empty";
//        }
//        ossDataMoveService.ossDateMove(type);
//        return "moveDate Success";
//    }

    @SignIgnore
    @VisitorAccessible
    @RequestMapping(value = "/updateV2/{type}", method = RequestMethod.GET)
    public String updateV2(@PathVariable("type") Integer type) {
        if (type == null) {
            return "type can't be empty";
        }
//        ossDataMoveService.updateV2(type);
        return "moveDate Success";
    }


    public static void main(String[] args) {
        String s3AccessKeyId = "AKIAZ4ZGT6V2VUNKVHV2";
        String s3AccessKeySecret = "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";
        String s3BucketName = "dc-imgs";

        BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3AccessKeyId, s3AccessKeySecret);

        AmazonS3 s3 = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                .withRegion(Regions.AP_SOUTH_1)
                .build();

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("image/"+"jpeg"); //type为设置上传图片的类型，jpg、png，如果不设置下载下来使用是会打不开
        try {
//            String path = this.getClass().getClassLoader().getResource("11111.jpeg").getPath();
            FileInputStream inputStream = new FileInputStream("/Users/yujianfu/Desktop/11111.jpeg");  //path为本地保存图片的路径，eg:   E:/test.jpg
            metadata.setContentLength(inputStream.available());
            PutObjectResult putObjectResult = s3.putObject(s3BucketName, "44444.jpeg", inputStream, metadata);//key代表你上传的文件的唯一标识
            System.err.println(111);
        } catch (IOException e) {
            e.printStackTrace();
        }


//        Long filelength = file.length(); // 获取文件长度
//        byte[] filecontent = new byte[filelength.intValue()];
//        try {
//            InputStream in = new FileInputStream(file);
//            in.read(filecontent);
//            in.close();
//            String fileName = "test1989919.jpeg";
//            uploadFile(in, fileName, "image/jpeg");
//
//            String finaleUrl = "http://cashmama.s3.ap-south-1.amazonaws.com/" + fileName;
//
//            System.err.println(finaleUrl);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }


    }

    public static void uploadFile(InputStream inputStream, String fileName, String contentType) {


        String s3AccessKeyId = "AKIAZ4ZGT6V2VUNKVHV2";
        String s3AccessKeySecret = "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";
        String region = "ap-south-1";
        String s3BucketName = "dc-imgs";


        BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3AccessKeyId, s3AccessKeySecret);
        AmazonS3 s3 = (AmazonS3) ((AmazonS3ClientBuilder) ((AmazonS3ClientBuilder) AmazonS3ClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds)))
                .withRegion(Regions.fromName(region))).build();
        ObjectMetadata meta = new ObjectMetadata();
        try {
            meta.setContentLength(inputStream.available());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotEmpty(contentType)) {
            meta.setContentType(contentType);
        }

        PutObjectRequest request = new PutObjectRequest(s3BucketName, fileName, inputStream, meta);
        request.withCannedAcl(CannedAccessControlList.PublicRead);

        try {
            s3.putObject(request);
        } catch (Exception var9) {
            LOGGER.error(var9.getMessage(), var9);
            throw var9;
        }
    }
}
